package cn.kgc.shiro.web.config;

import cn.kgc.shiro.web.entity.User;
import cn.kgc.shiro.web.entity.UserRole;
import cn.kgc.shiro.web.mapper.RoleMapper;
import cn.kgc.shiro.web.mapper.UserMapper;
import cn.kgc.shiro.web.mapper.UserRoleMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 课工场
 * @date 2024/6/4
 * @description
 */
public class CustomerRealm extends AuthorizingRealm {

    @Resource
    private UserMapper userMapper;

    @Resource
    private UserRoleMapper userRoleMapper;

    @Resource
    private RoleMapper roleMapper;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        String primaryPrincipal = (String) principals.getPrimaryPrincipal();
        User user = userMapper.selectOneByUsername(primaryPrincipal);

        Integer id = user.getId();

        LambdaQueryWrapper<UserRole> lambda = new QueryWrapper<UserRole>().lambda();
        lambda.eq(UserRole::getUid,id);

        List<Integer> rids = userRoleMapper.selectList(lambda).stream()
                .map(ur -> ur.getRid())
                .collect(Collectors.toList());

        System.out.println("rids = " + rids);

        List<String> roleNames = roleMapper.selectBatchIds(rids).stream()
                .map(role -> role.getRoleName())
                .collect(Collectors.toList());


        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addRoles(roleNames);

        return simpleAuthorizationInfo;
    }


    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        String username = usernamePasswordToken.getUsername();

        // 根据用户名查询数据库
        User user = userMapper.selectOneByUsername(username);
        if (ObjectUtils.isNotNull(user)){
            SimpleAuthenticationInfo simpleAuthenticationInfo =
                    new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(),
                            ByteSource.Util.bytes(user.getSalt()), this.getName());

            return simpleAuthenticationInfo;
        }
        return null;
    }
}
